import React from 'react'
import {connect} from 'react-redux'
import {messages,queryCurrencyPrecision} from "share/common";
import constants from "share/constants";
import SearchArea from 'components/search-area';
import { Button, Input, Popover, Tag, message } from 'antd';
import Stations from 'components/template/proxies/stations';
import moment from "moment";
import Proxies from 'components/template/proxies/proxies';
import 'styles/request/request.scss';
import menuRoute from "routes/menuRoute";
import borrowService from 'containers/loan-billing/borrow-and-return.service';
import debounce from 'lodash.debounce';
import Condition from 'components/condition';
import Importer from 'components/template/importer';
import ResizeTable from 'components/resize-table';
const { If } = Condition;
const Search = Input.Search;

class MyBorrow extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      checkboxListForm: [{
        id: 'status',
        single: true,
        items: [{
          label: messages('common.column.status'),
          key: 'statusWithReject',
          checked: ['1001100210031004100510061007100810111012'],
          options: [
            {label: messages('common.all'), value: '1001100210031004100510061007100810111012', operate: ''},      //全部
            ...constants.loanStatus
          ]
        }]
      }],
      searchForm: [
        {
          type: 'items', id: 'dateRange', items: [
            {type: 'date', id: 'startDate', label: messages('common.start.date')},
            {type: 'date', id: 'endDate', label: messages('common.end.date')}
          ]
        },
        {
          type: 'combobox',
          id: 'applicantOIDs',
          label: messages('common.applicant'),
          placeholder: messages('loan-billing.key46')/*请输入姓名／工号*/,
          options: [],
          searchUrl: `/api/users/v3/search?page=0&size=9999`,
          method: 'get',
          searchKey: 'keyword',
          labelKey: 'fullName',
          valueKey: 'userOID',
          renderOption: option => (`${option.eid}-${option.employeeID}-${option.fullName}${(option.status != 1001 ? messages('loan-billing.key47')/*(已离职)*/ : '')}`)
        },
        {
          type: 'select', id: 'currencyCode', label: messages('common.currency'), options: [],
          getUrl: `/api/currency/status/query/by/setOfBooksId?userOId=${props.user.userOID}`,
          labelKey: 'currency', valueKey: 'currency', method: 'get'
        },
        {
          type: 'input', id: 'title', label: messages('loan-billing.key119')/*事由*/
        }
      ],
      data: [],
      page: 0,
      size: 10,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      searchParams: {status: '1001100210031004100510061007100810111012'},
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', render: (value, record, index) =>
            index + 1 + this.state.size * this.state.page, width: 48},
        {title: messages('common.submit.date')/*提交日期*/, dataIndex: 'createdDate',width: 120, render: (value) => moment(value).format('YYYY-MM-DD')},
        {title: messages('common.applicant')/*申请人*/, dataIndex: 'applicantName'},
        {title: messages('common.document.name')/*单据名称*/, dataIndex: 'formName', render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'},
        {title: messages('common.document.code')/*单号*/, dataIndex: 'businessCode'},
        {title: messages('common.subjectmatter')/*事由*/, dataIndex: 'title', render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'},
        {title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 48},
        {title: messages('common.amount')/*金额*/, dataIndex: 'currencyAmount', align: 'right', width: '7%', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        { title: messages('loan-billing.key153')/*本币币种*/, dataIndex: 'baseCurrencyCode' },
        {title: messages('finance-7.key139')/*已付款金额*/, dataIndex: 'baseCurrencyAmount', align: 'right',width: '8%',render: (value,record) => {
          let needShow = [1005,1006,1007];
          let res = '-';
          needShow.indexOf(record.status) > -1 && (res = this.filterMoney(value,queryCurrencyPrecision(record.baseCurrencyCode)));
          return res;
        }},
        {title: messages('common.column.status'), dataIndex: 'status', width: props.language.code === 'zh_cn' ? '8%' : '13%',
          render: (value, record) => {
            let applicationType = 2005; //申请单
            let text;
            let color;
            if (record.closed || (record.applicationParticipant && record.applicationParticipant.closed === 1)) {
              text = messages('constants.documentStatus.yet.disable'/*已停用*/);
              color = '#d9d9d9'
            } else {
              text = constants.getTextByValue(String(value + '' + applicationType), 'documentLoanStatus') ||
                constants.getTextByValue(String(value + '' + record.rejectType), 'documentLoanStatus') ||
                constants.getTextByValue(String(value), 'documentLoanStatus');
              color = constants.getTextByValue(String(value + '' + applicationType), 'documentLoanStatus', 'color') ||
                constants.getTextByValue(String(value + '' + record.rejectType), 'documentLoanStatus', 'color') ||
                constants.getTextByValue(String(value), 'documentLoanStatus', 'color')
            };
            return <Tag color={color} >{text}</Tag>
          }},
      ],
      loading: false,
      isNeedImporter: this.checkFunctionProfiles('loanline.excel.import.enable',[true]),
      showOfferImportModal: false,
      newBorrow: menuRoute.getRouteItem('new-borrow'),
      loanDetail: menuRoute.getRouteItem('loan-detail'),
      editBorrow: menuRoute.getRouteItem('edit-borrow')
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentWillMount() {
    this.getForms();
    this.getList();
  }

  //初始数据
  getList = () => {
    const { searchParams, page, size, pagination } = this.state;
    this.setState({loading:true});
    borrowService.getMyLoanTable(searchParams,page,size).then(res => {
      pagination.total =  Number(res.headers['x-total-count']) || 0;
      pagination.current = page + 1;
      pagination.onChange = this.onChangePaper;
      this.setState({
        data: res.data,
        loading: false,
        pagination
      })
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading:false});
    });
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.size)
      this.setState({
        page: 0,
        size: size
      },() => {
        this.getList()
      })
  };

  //分页
  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getList()
      })
    }
  };

  //获得表单
  getForms = () => {
    const { checkboxListForm } = this.state;
    let formCheckBoxItem = {};
    let options = [{label: messages('common.all'), value: 'all'}];
    formCheckBoxItem.id = 'formOID';
    formCheckBoxItem.single = true;
    borrowService.getMyDocumentType(104, undefined, true, this.props.applicationFormType).then(res => {
      res.data.map(item => {
        options.push({label: item.formName, value: item.formOID})
      });
      formCheckBoxItem.items = [{label: messages('common.document.name'), key: 'formOID', options, checked: ['all']}];
      checkboxListForm.push(formCheckBoxItem);
      this.setState({ checkboxListForm });
    }).catch(e => {
      message.error(e.response.data.message);
    });
  };

  //搜索
  search = (values) => {
    values.formOID === 'all' && (delete values.formOID);
    values.formOID && (values.formOIDs = [values.formOID]);
    delete values.formOID;
    values.applicantOIDs && (values.applicantOIDs = [values.applicantOIDs]);
    values.startDate && (values.startDate = moment(values.startDate).format('YYYY-MM-DD 00:00:00'));
    values.endDate && (values.endDate = moment(values.endDate).format('YYYY-MM-DD 23:59:59'));
    this.setState({ searchParams: values, page: 0 },() => {
      this.getList()
    })
  };

  //清楚搜索条件
  clear = () => {
    this.setState({
      searchParams: {status: '1001100210031004100510061007100810111012'},
      page: 0,
    },() => {
      this.getList()
    })
  };

  //搜索单号
  handleSearch = (value) => {
    let { searchParams } = this.state;
    searchParams.businessCode = value;
    this.setState({
      page: 0,
      searchParams
    }, () => {
      this.getList();
    })
  };

  //行扩展
  renderAllExpandedRow = (record) => {
    let result = null;
    record.rejectReason && (result = <div>{messages('loan-billing.key57')/*审批驳回*/}:{record.rejectReason}</div>);
    return result;
  };

  //新建借款单
  handleNewBorrow = (value, jobId, applicantOID, ifProxy) => {
    if (ifProxy) {
      this.context.router.push(this.state.newBorrow.url.replace(':formOID', value).replace(':jobId', jobId).replace(':applicantOID', applicantOID).replace(':ifProxy', 1));
    } else {
      this.context.router.push(this.state.newBorrow.url.replace(':formOID', value).replace(':jobId', jobId).replace(':applicantOID', applicantOID));
    }
  };

  //进详情 type === 2005 单行借款单 2006 多行借款单
  handleRowClick = (record) => {
    if(record.status === 1001 && record.formType === 2005){
      this.context.router.push(this.state.editBorrow.url.replace(':formOID',record.formOID).replace(':loanBillOID',record.loanBillOID));
    }else{
      this.context.router.push(this.state.loanDetail.url.replace(':formOID',record.formOID).replace(':loanBillOID',record.loanBillOID));
    }
  };

  openOfferImport = (flag) => {
    this.setState({showOfferImportModal: flag});
  };

  importOfferFile = () => {
    this.openOfferImport(false);
    this.getList();
  };

  render(){
    const { checkboxListForm, searchForm, pagination, columns, data, loading, isNeedImporter, showOfferImportModal } = this.state;
    return(
      <div className='application-list'>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
          checkboxListForm={checkboxListForm}
        />
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', {total: pagination.total})/*共搜索到 {pagination.total} 条数据*/}
          </div>
          <div className="table-header-buttons">
            <Stations formType={'104'} onOk={this.handleNewBorrow}/>
            <Proxies formType={'104'} onOk={this.handleNewBorrow}/>
            <If value={isNeedImporter}>
              <Button onClick={() => this.openOfferImport(true)}>{messages('loan-billing.key102')/*批量借款*/}</Button>
            </If>
            <Search
              className="input-search"
              placeholder={messages('loan-billing.key59')/*请输入借款单号*/}
              onChange={(e) => this.handleSearch(e.target.value)}
            />
          </div>
        </div>
        <ResizeTable
          rowKey="loanBillOID"
          columns={columns}
          dataSource={data}
          pagination={pagination}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          expandedRowRender={this.renderAllExpandedRow}
          loading={loading}
          bordered
          rowClassName={
            record => record.rejectReason ? '' : 'row-expand-display-none'
          }
          size="middle"
        />
        <Importer
          visible={showOfferImportModal}
          title={messages('loan-billing.key102')/*批量借款*/}
          templateUrl={`/api/loanBill/template/download`}
          uploadUrl={`/api/loanBill/batch/uploading`}
          errorUrl={`/api/loanBill/batch/upload/error`}
          listenUrl={`/api/batch/transaction/logs/customenumerationitem`}
          fileName={messages('loan-billing.key103')/*电子表格*/}
          onOk={this.importOfferFile}
          isSpecial
          afterClose={() => this.openOfferImport(false)}
        />
      </div>
    )
  }
}

MyBorrow.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    language: state.main.language,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(MyBorrow);
